<template>
  <div class="smart-search-layout">
    <!-- 智能搜索界面 -->
    <div class="search-interface" :class="{ 'search-focused': searchFocused }">
      <div class="search-content">
        <!-- Logo和标题 -->
        <div class="search-brand">
          <img src="@/assets/logo.png" alt="Logo" class="search-logo" />
          <h1 class="search-title">Big ERP</h1>
          <p class="search-subtitle">智能搜索 · 快速导航</p>
        </div>

        <!-- 搜索框 -->
        <div class="search-box-container">
          <div class="search-box">
            <el-icon class="search-icon" :size="24"><Search /></el-icon>
            <input
              ref="searchInputRef"
              v-model="searchKeyword"
              type="text"
              placeholder="搜索功能、数据、或描述你想做什么..."
              class="search-input"
              @focus="searchFocused = true"
              @blur="handleSearchBlur"
              @input="handleSearchInput"
              @keydown.enter="handleEnter"
              @keydown.down="handleArrowDown"
              @keydown.up="handleArrowUp"
            />
            <div class="search-shortcuts">
              <kbd>Ctrl</kbd>+<kbd>K</kbd>
            </div>
          </div>

          <!-- 搜索建议 -->
          <transition name="slide-down">
            <div v-if="searchKeyword && searchResults.length > 0" class="search-results">
              <div class="results-header">
                <span>找到 {{ searchResults.length }} 个结果</span>
                <el-button text size="small" @click="clearSearch">清空</el-button>
              </div>
              <div class="results-list">
                <div
                  v-for="(result, index) in searchResults"
                  :key="result.path"
                  class="result-item"
                  :class="{ selected: selectedIndex === index }"
                  @click="selectResult(result)"
                  @mouseenter="selectedIndex = index"
                >
                  <div class="result-icon" :style="{ background: result.color }">
                    <el-icon :size="20">
                      <component :is="result.icon" />
                    </el-icon>
                  </div>
                  <div class="result-info">
                    <div class="result-title">{{ result.title }}</div>
                    <div class="result-path">{{ result.breadcrumb }}</div>
                  </div>
                  <div class="result-type">
                    <el-tag size="small">{{ result.type }}</el-tag>
                  </div>
                </div>
              </div>
            </div>
          </transition>
        </div>

        <!-- 快速入口 -->
        <div class="quick-access" v-if="!searchKeyword">
          <h3 class="access-title">快速入口</h3>
          <div class="access-grid">
            <div
              v-for="item in quickAccessItems"
              :key="item.path"
              class="access-item"
              @click="navigateTo(item.path)"
            >
              <div class="access-icon" :style="{ background: item.color }">
                <el-icon :size="32">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="access-title-text">{{ item.title }}</div>
              <div class="access-desc">{{ item.description }}</div>
            </div>
          </div>
        </div>

        <!-- 最近访问 -->
        <div class="recent-access" v-if="!searchKeyword && recentItems.length > 0">
          <h3 class="access-title">最近访问</h3>
          <div class="recent-list">
            <div
              v-for="item in recentItems"
              :key="item.path"
              class="recent-item"
              @click="navigateTo(item.path)"
            >
              <el-icon :size="20" :color="item.color">
                <component :is="item.icon" />
              </el-icon>
              <span class="recent-title">{{ item.title }}</span>
              <span class="recent-time">{{ item.time }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部提示 -->
      <div class="search-footer">
        <div class="footer-tips">
          <span class="tip-item"><kbd>↑</kbd><kbd>↓</kbd> 选择</span>
          <span class="tip-item"><kbd>Enter</kbd> 打开</span>
          <span class="tip-item"><kbd>Esc</kbd> 清空</span>
        </div>
        <div class="footer-actions">
          <el-tooltip content="导航设置">
            <el-button circle size="small" @click="showNavigationSettings">
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 页面内容（覆盖模式） -->
    <transition name="page-fade">
      <div v-if="showPage" class="page-overlay">
        <div class="page-header">
          <el-button circle @click="backToSearch">
            <el-icon><HomeFilled /></el-icon>
          </el-button>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <div style="flex: 1;"></div>
          <el-dropdown @command="handleUserCommand">
            <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="page-main">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" :key="$route.fullPath" />
            </transition>
          </router-view>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import {
  Search, HomeFilled, ShoppingCart, Box, Money, UserFilled,
  DataBoard, Setting, Suitcase, TrendCharts, Van
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

const searchInputRef = ref(null)
const searchKeyword = ref('')
const searchFocused = ref(false)
const selectedIndex = ref(0)

const showPage = computed(() => {
  return route.path !== '/dashboard' && route.path !== '/'
})

// 快速入口
const quickAccessItems = ref([
  {
    path: '/member/members',
    title: '会员资料',
    description: '查看和管理会员',
    icon: markRaw(UserFilled),
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    path: '/sales/orders',
    title: '销售订单',
    description: '创建和管理订单',
    icon: markRaw(ShoppingCart),
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
  },
  {
    path: '/reports',
    title: '综合报表',
    description: '查看业务数据',
    icon: markRaw(DataBoard),
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
  },
  {
    path: '/inventory/stock',
    title: '库存查询',
    description: '实时库存监控',
    icon: markRaw(Box),
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
  }
])

// 最近访问
const recentItems = ref([
  { path: '/member/dashboard/1', title: '张三 - 会员详情', icon: markRaw(UserFilled), color: '#667eea', time: '5分钟前' },
  { path: '/reports/sales', title: '销售报表', icon: markRaw(TrendCharts), color: '#f5576c', time: '15分钟前' },
  { path: '/sales/orders', title: '销售订单', icon: markRaw(ShoppingCart), color: '#4facfe', time: '1小时前' }
])

// 搜索结果（模拟）
const allSearchableItems = ref([
  { path: '/member/members', title: '会员资料', breadcrumb: '会员管理 > 会员中心', type: '功能', icon: markRaw(UserFilled), color: '#667eea' },
  { path: '/member/dashboard/:id', title: '会员详情看板', breadcrumb: '会员管理 > 会员中心', type: '功能', icon: markRaw(DataBoard), color: '#667eea' },
  { path: '/member/checkin', title: '签到管理', breadcrumb: '会员管理 > 积分体系', type: '功能', icon: markRaw(UserFilled), color: '#667eea' },
  { path: '/reports', title: '综合报表', breadcrumb: '综合报表 > 报表中心', type: '功能', icon: markRaw(DataBoard), color: '#f5576c' },
  { path: '/sales/orders', title: '销售订单', breadcrumb: '销售管理', type: '功能', icon: markRaw(ShoppingCart), color: '#4facfe' },
  { path: '/inventory/stock', title: '库存查询', breadcrumb: '库存管理', type: '功能', icon: markRaw(Box), color: '#43e97b' },
  { path: '/extensions/plugin-market', title: '插件市场', breadcrumb: '扩展中心 > 插件市场', type: '功能', icon: markRaw(Suitcase), color: '#a8edea' },
  { path: '/extensions/theme-store', title: '主题商店', breadcrumb: '扩展中心 > 主题商店', type: '功能', icon: markRaw(Suitcase), color: '#fed6e3' }
])

const searchResults = computed(() => {
  if (!searchKeyword.value) return []
  
  const keyword = searchKeyword.value.toLowerCase()
  return allSearchableItems.value.filter(item =>
    item.title.toLowerCase().includes(keyword) ||
    item.breadcrumb.toLowerCase().includes(keyword)
  ).slice(0, 8)
})

const breadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    path: item.path,
    title: item.meta.title
  }))
})

const navigateTo = (path) => {
  router.push(path)
}

const backToSearch = () => {
  router.push('/dashboard')
}

const handleSearchBlur = () => {
  setTimeout(() => {
    searchFocused.value = false
  }, 200)
}

const handleSearchInput = () => {
  selectedIndex.value = 0
}

const handleEnter = () => {
  if (searchResults.value.length > 0 && selectedIndex.value >= 0) {
    selectResult(searchResults.value[selectedIndex.value])
  }
}

const handleArrowDown = (e) => {
  e.preventDefault()
  if (selectedIndex.value < searchResults.value.length - 1) {
    selectedIndex.value++
  }
}

const handleArrowUp = (e) => {
  e.preventDefault()
  if (selectedIndex.value > 0) {
    selectedIndex.value--
  }
}

const selectResult = (result) => {
  router.push(result.path)
  searchKeyword.value = ''
}

const clearSearch = () => {
  searchKeyword.value = ''
}

const showNavigationSettings = () => {
  // 触发导航设置对话框
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const handleUserCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const userStore = useUserStore()
      userStore.logout()
      router.push('/login')
      ElMessage.success('已退出登录')
    }).catch(() => {})
  } else if (command === 'profile') {
    router.push('/system/user-settings')
  }
}

// 自动聚焦搜索框
watch(showPage, (val) => {
  if (!val) {
    setTimeout(() => {
      searchInputRef.value?.focus()
    }, 100)
  }
})

onMounted(() => {
  searchInputRef.value?.focus()
})
</script>

<style scoped>
.smart-search-layout {
  position: relative;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 搜索界面 */
.search-interface {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  transition: all 0.4s ease;
}

.search-interface.search-focused {
  justify-content: flex-start;
  padding-top: 15vh;
}

.search-content {
  width: 100%;
  max-width: 800px;
}

.search-brand {
  text-align: center;
  margin-bottom: 48px;
  animation: brandIn 0.8s ease;
}

@keyframes brandIn {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.search-logo {
  height: 80px;
  margin-bottom: 24px;
  filter: drop-shadow(0 8px 24px rgba(0, 0, 0, 0.2));
}

.search-title {
  font-size: 48px;
  font-weight: 700;
  color: white;
  margin: 0 0 12px 0;
  text-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.search-subtitle {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
}

/* 搜索框 */
.search-box-container {
  position: relative;
  animation: searchBoxIn 0.8s ease 0.2s both;
}

@keyframes searchBoxIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 16px 64px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.search-box:focus-within {
  box-shadow: 0 20px 80px rgba(0, 0, 0, 0.3);
  transform: translateY(-4px);
}

.search-icon {
  color: #909399;
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 18px;
  color: #303133;
  background: transparent;
}

.search-input::placeholder {
  color: #c0c4cc;
}

.search-shortcuts {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.search-shortcuts kbd {
  padding: 4px 8px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  font-size: 12px;
  font-family: monospace;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 搜索结果 */
.search-results {
  margin-top: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 16px 64px rgba(0, 0, 0, 0.2);
  max-height: 500px;
  overflow-y: auto;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.result-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover,
.result-item.selected {
  background: #f5f7fa;
}

.result-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.result-info {
  flex: 1;
}

.result-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.result-path {
  font-size: 13px;
  color: #909399;
}

/* 快速入口 */
.quick-access,
.recent-access {
  margin-top: 48px;
  animation: fadeInUp 0.8s ease 0.4s both;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.access-title {
  color: white;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 20px 0;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.access-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.access-item {
  padding: 24px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.access-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateY(-5px);
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
}

.access-icon {
  width: 64px;
  height: 64px;
  margin: 0 auto 16px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.access-title-text {
  font-size: 16px;
  font-weight: 600;
  color: white;
  margin-bottom: 8px;
}

.access-desc {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

/* 最近访问 */
.recent-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.recent-item:hover {
  background: rgba(255, 255, 255, 0.25);
  transform: translateX(5px);
}

.recent-title {
  flex: 1;
  font-size: 14px;
}

.recent-time {
  font-size: 12px;
  opacity: 0.8;
}

/* 底部提示 */
.search-footer {
  position: fixed;
  bottom: 32px;
  left: 50%;
  transform: translateX(-50%);
}

.footer-tips {
  display: flex;
  gap: 24px;
  color: white;
  font-size: 13px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tip-item kbd {
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面覆盖层 */
.page-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: #f0f2f5;
  z-index: 10;
  display: flex;
  flex-direction: column;
}

.page-header {
  height: 60px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  padding: 0 24px;
  gap: 16px;
}

.page-main {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  height: 0;
}

/* 动画 */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.page-fade-enter-active,
.page-fade-leave-active {
  transition: all 0.4s ease;
}

.page-fade-enter-from,
.page-fade-leave-to {
  opacity: 0;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式 */
@media (max-width: 1200px) {
  .access-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .search-logo {
    height: 60px;
  }
  
  .search-title {
    font-size: 36px;
  }
  
  .access-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .search-interface {
    padding: 20px;
  }
}
</style>


